from django.shortcuts import render,reverse
from django.http import HttpResponse,JsonResponse
from myadmin.models import Users,Types
from myadmin import upload
from django.contrib.auth.hashers import make_password, check_password
import os
from django.db.models import Q
from django.core.paginator import Paginator
# Create your views here.


def typeadd(request):
    # 先获取所有的商品分类,显示到add.html的下拉框里
    db = Getall()
    # 数据显示排序 和 缩进 最后再处理
    return render(request,'admin/type/add.html',{'db':db})

def typeinsert(request):
    # 获取下拉框pid选择的value值(id) 作为 新建对象的pid
    num = request.POST['pid']
    try:
        ob = Types()
        ob.name = request.POST['name']
        # ob.path 如果是顶级分类,为0 如果是子级分类,需要拼接其父类的path+ 自己的pid
        if num == '0':          # 注意字符串 数字的类型
            ob.pid = 0
            ob.path = '0,'
        else:
            ob.pid = num
            ob2 = Types.objects.get(id=num)
            ob.path = ob2.path + str(num)+','
        ob.save()
        return HttpResponse('<script>alert("添加成功");location.href="{}"</script>'.format(reverse('type_list')))
    except:
        return HttpResponse('<script>alert("添加失败");location.href="{}"</script>'.format(reverse('type_add')))


def typelist(request):
    # 搜索展示:以类名为搜索条件
    keywords = request.GET.get('keywords', '')
    db = Getall().filter(name__contains=keywords)

    # 表单显示自定义个数化以下,可封装起来
    for i in db:
        # 缩进
        n = int(len(i.path)/2) - 1
        i.name = '|--'*n + i.name
        # 把所属父类的显示成字符串形式
        if i.pid == 0:
            i.pname = '顶级分类'
        else:
            # 把父类查询出来
            obj = Types.objects.get(id=i.pid)
            i.pname = obj.name


    # print(db)
    #对以上操作获取的数据db做分页展示,需要引入分页类
    pageobj = Paginator(db,8)  #实例化分页对象
    # print(pageobj)
    p = int(request.GET.get('p',1)) #a标签p传参
    pdata = pageobj.page(p)   #当前页数据
    # print(pdata)
    pagelist = pageobj.page_range   #页码列表
    pageallnum = pageobj.num_pages   #直接分页对象获取总页数
    print(pdata)
    # pageallnum = pdata.paginator.num_pages    #当前页数据也可以获取总页数
    # print(pageallnum)

    context = {'db':pdata,'pagelist':pagelist,'num':pageallnum}

    return render(request,'admin/type/list.html',context)









def typeedit(request,id):
    # 获取点击的对象和所有的记录
    # 拿到前台select中遍 用来锁定点击对象的父类. selected  子类pid 等于 父类pid  并且让其余选项disable
    ob = Types.objects.get(id=id)
    oball = Getall()
    content = {'db':ob,'oball':oball}
    return render(request,'admin/type/edit.html',content)


def typesave(request):
    # 获取传过来的数据
    # print(request.POST)
    try:
        ob = Types.objects.get(id=request.POST['id'])
        ob.name = request.POST.get('name')
        ob.save()
        return HttpResponse('<script>alert("修改成功");location.href="{}"</script>'.format(reverse('type_list')))
    except:
        return HttpResponse('<script>alert("修改失败");location.href="/admin/type/edit/'+request.POST['id']+'"</script>')


def typedel(request):
    # print(request.GET.get('id'))
    ob1 = Types.objects.filter(pid=request.GET.get('id'))
    # 没有子类,子类为空
    if ob1:
        return JsonResponse({'status': 1, 'msg': '当前类下还有子类,不能删除'})
    ob = Types.objects.get(id=request.GET.get('id'))
    ob.delete()
    print(ob)
    return JsonResponse({'status': 0, 'msg': '删除成功'})
    # 方式1: ajax 删除



    ## 方式2: 后台删除
    # # 判断该对象有没有子类有就不能删,没有就可以删
    # ob1 = Types.objects.filter(pid=id)
    # print(ob1)
    # if not ob1 :
    #     ob = Types.objects.get(id=id)
    #     ob.delete()
    #     return HttpResponse('<script>alert("删除成功");location.href="{}"</script>'.format(reverse('type_list')))
    # else:
    #     return HttpResponse('<script>alert("删除失败,该类别有子类");location.href="{}"</script>'.format(reverse('type_list')))










# 封装获取所有分类的函数,排序 缩进 都给予显示

def Getall():
    # 不用拼接方式 防止sql注入
    ob = Types.objects.extra(select={'paths': 'concat(path,id)'}).order_by('paths')
    for i in ob:
        # 缩进
        n = int(len(i.path)/2) - 1
        i.name = '|--'*n + i.name

        # 把所属父类的显示成字符串形式
        if i.pid == 0:
            i.pname = '顶级分类'
        else:
            # 把父类查询出来
            obj = Types.objects.get(id=i.pid)
            i.pname = obj.name
    return ob
